﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using LdExpress;
using System.Data;
using MySql.Data.MySqlClient;

public partial class Customer : System.Web.UI.Page
{
    string strPageID = "page_number";
    public int NumOfItemsPerPage = 20;
    public int nPermissions = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["pic"] != null && int.Parse(Session["pic"].ToString()) > 0)
        {
            if (Session["pic"] != "") nPermissions = int.Parse(Session["pic"].ToString());
        }
        if (nPermissions < 1) Response.Redirect("Login.aspx"); ;
        if (!Page.IsPostBack)
        {
            if (Request.UrlReferrer != null)
                Session["UrlReferrer"] = Request.UrlReferrer.ToString();
            else
            {
                Session["UrlReferrer"] = "http://bachvietshipping.vn/CustomerRelation.aspx";
            }
            long cusid = 0;
            if (!string.IsNullOrEmpty(Request.Params["picid"]))
            {
                cusid = long.Parse(Request.Params["picid"]);
                LoadInfo(cusid);

            }
            if (Request.QueryString["action"] != null && Request.QueryString["action"].ToString().ToLower() == "deletemeeting" && Request.QueryString["mid"] != null)
            {
                DiaryEachMeeting obj = new DiaryEachMeeting();
                long mid = long.Parse(Request.QueryString["mid"].ToString());
                obj.ID = mid;
                obj.Delete(GV.cn, GV.trans);
                string url = "Customer.aspx?picid=" + Request.QueryString["picid"].ToString();
                if (Request.QueryString["id"] != null)
                    url += "&id=" + Request.QueryString["id"].ToString();
                Response.Redirect(url);
            }
            #region Build List Customer Offer Prices
            int nNumOfPages = 0, nPage = 1;
            nNumOfPages = 0;
            try
            {
                if (Request.QueryString[strPageID] != null)
                    nPage = int.Parse(Request.QueryString[strPageID]);
            }
            catch
            {
                nPage = 1;
            }
            try
            {
                if (Request.QueryString[strPageID] != null)
                    nPage = int.Parse(Request.QueryString[strPageID]);
            }
            catch { }
            if (nPage <= 0) nPage = 1;
            DataTable dtList = null;
            BuildListDiaryEachMeeting(NumOfItemsPerPage, nPage, out nNumOfPages, out dtList);
            if (nPage > nNumOfPages) nPage = 1;

            rpDiaryEachMeeting.DataSource = dtList;
            rpDiaryEachMeeting.DataBind();
            if (nPermissions < 3) LoadMeetingReadOnly();
            #endregion
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session["UrlReferrer"] == null)
            return;
        string referurl = Session["UrlReferrer"].ToString();
        Customers customer = new Customers();
        int numberofpage = 0;
        if (!string.IsNullOrEmpty(Request.Params["picid"]) && int.Parse(Request.Params["picid"].ToString()) > 0)
        {
            //update
            customer.ID = long.Parse(Request.Params["picid"]);
            string strcondition = " AND PicID= " + customer.ID;

            int totalitem = 0;

            DataSet ds;
            if (referurl.ToLower().Contains("customerrelation.aspx"))
            {
                CustomerRelation.GetList(strcondition, "", 1, 1, out numberofpage, out totalitem, out ds, GV.cn, GV.trans);
            }
            else if (referurl.ToLower().Contains("coloader.aspx"))
            {
                CoLoader.GetList(strcondition, "", 1, 1, out numberofpage, out ds, GV.cn, GV.trans);
            }
            else if (referurl.ToLower().Contains("carrcontact.aspx"))
            {
                CarrContact.GetList(strcondition, "", 1, 1, out numberofpage, out ds, GV.cn, GV.trans);
            }
            if (numberofpage > 1)//tao moi trong truong hop dupplicate
            {
                customer.ID = -1;
                customer.GUID = Guid.NewGuid().ToString();
            }
            else
            {
                customer.Load(GV.cn, GV.trans);
            }
        }
        else
        {
            //adnew
            customer.ID = -1;
            customer.GUID = Guid.NewGuid().ToString();
            string frompage = "";
            string idpage = "";
        }

        string HoTen = txtHoten.Text;
        customer.HoTen = HoTen;
        customer.BirthDay = txtBirthDay.Text;
        string QueQuan = txtQueQuan.Text;
        customer.QueQuan = QueQuan;
        string DiaChiThuongTru = txtThuongTru.Text;
        customer.DiaChiThuongTru = DiaChiThuongTru;
        customer.KinhNghiem = txtNangKhieuCon.Text;
        string TrinhDoHocVan = txtTrinhDo.Text;
        customer.TrinhDoHocVan = TrinhDoHocVan;
        string SoThich = txtSoThich.Text;
        customer.SoThich = SoThich;
        string VC_QueQuan = txtVCQue.Text;
        customer.VC_QueQuan = VC_QueQuan;
        string VC_NgheNghiep = txtVCNgheNghiep.Text;
        customer.VC_NgheNghiep = VC_NgheNghiep;
        string VC_NangKhieu = txtVCNangKhieu.Text;
        customer.VC_NangKhieu = VC_NangKhieu;
        string ConCai = txtConcai.Text;
        customer.ConCai = ConCai;
        string Note = txtNote.Text;
        customer.Note = Note;
        customer.BangCapCaoNhat = txtVitri.Text;
        try
        {
            customer.LoaiKhachHang = int.Parse(cbLoaiKhachHang.SelectedValue);
        }
        catch { }
        DateTime lastupdate = DateTime.Now;
        customer.LastUpdate = lastupdate;

        long cusid = customer.Save(GV.cn, GV.trans);
        long cid = long.Parse(Request.Params["id"]);
        string _customerid = Request.Params["picid"];
        if (referurl.ToLower().Contains("customerrelation.aspx"))
        {
            CustomerRelation cr = new CustomerRelation(cid);
            cr.Load(GV.cn, GV.trans);

            if (string.IsNullOrEmpty(_customerid) || _customerid == "0" || numberofpage > 1)
            {

                cr.PicID = cusid;
                //cr.Pic = customer.HoTen;
            }
            else
            {
                //cr.Pic = customer.HoTen;
            }
            cr.Save(GV.cn, GV.trans);
        }
        else if (referurl.ToLower().Contains("coloader.aspx"))
        {
            CoLoader col = new CoLoader(cid);
            col.Load(GV.cn, GV.trans);

            if (string.IsNullOrEmpty(_customerid) || _customerid == "0" || numberofpage > 1)
            {

                col.PicID = cusid;
            }
            else
            {
                //col.Pic_sales = customer.HoTen;
            }
            col.Save(GV.cn, GV.trans);
        }
        else if (referurl.ToLower().Contains("carrcontact.aspx"))
        {
            CarrContact col = new CarrContact(cid);
            col.Load(GV.cn, GV.trans);

            if (string.IsNullOrEmpty(_customerid) || _customerid == "0" || numberofpage > 1)
            {

                col.PicID = cusid;
                //col.Pic_sales = customer.HoTen;
            }
            else
            {
                //col.Pic_sales = customer.HoTen;
            }
            col.Save(GV.cn, GV.trans);
        }
        else if (referurl.ToLower().Contains("truckersale.aspx"))
        {
            TruckerSale col = new TruckerSale(cid);
            col.Load(GV.cn, GV.trans);

            if (string.IsNullOrEmpty(_customerid) || _customerid == "0" || numberofpage > 1)
            {

                col.PicID = cusid;
                //col.Pic_sales = customer.HoTen;
            }
            else
            {
                //col.Pic_sales = customer.HoTen;
            }
            col.Save(GV.cn, GV.trans);
        }

        //Save Customer Meeting
        foreach (RepeaterItem item in rpDiaryEachMeeting.Items)
        {
            string aID = ((HiddenField)item.FindControl("ID")).Value.Trim();
            string aDesc = ((TextBox)item.FindControl("Description")).Text.Trim();
            string aMeeting = ((TextBox)item.FindControl("MeetingPlace")).Text.Trim();
            if (aID.Length > 0)//Update
            {
                bool isPlanSave = false;
                DiaryEachMeeting obj = new DiaryEachMeeting();
                obj.ID = long.Parse(aID);
                obj.Load(GV.cn, GV.trans);
                if (obj.Description != aDesc)
                {
                    obj.Description = aDesc;
                    isPlanSave = true;
                }
                if (obj.MeetingPlace != aMeeting)
                {
                    obj.MeetingPlace = aMeeting;
                    isPlanSave = true;
                }
                if (isPlanSave)
                {
                    obj.LastUpdate = DateTime.Now;
                    obj.Save(GV.cn, GV.trans);
                }

            }
            if (aMeeting.Length > 0 && aID.Length == 0)
            {
                DiaryEachMeeting obj = new DiaryEachMeeting();
                obj.ID = -1;
                obj.Description = aDesc;
                obj.CustomerID = cusid;
                obj.MeetingPlace = aMeeting;
                obj.LastUpdate = DateTime.Now;
                obj.UserID = long.Parse(Session["logined_id"].ToString());
                obj.Save(GV.cn, GV.trans);
            }
        }
        ScriptManager.RegisterStartupScript(this, GetType(), "key", "ReloadParent();", true);
    }
    private void LoadInfo(long customerid)
    {
        Customers customer = new Customers();
        customer.ID = customerid;
        customer.Load(GV.cn, GV.trans);

        txtHoten.Text = customer.HoTen;
        txtBirthDay.Text = customer.BirthDay;
        txtQueQuan.Text = customer.QueQuan;
        txtThuongTru.Text = customer.DiaChiThuongTru;
        txtNangKhieuCon.Text = customer.KinhNghiem;
        txtTrinhDo.Text = customer.TrinhDoHocVan;
        txtSoThich.Text = customer.SoThich;
        //gia dinh
        txtVCQue.Text = customer.VC_QueQuan;
        txtVCNgheNghiep.Text = customer.VC_NgheNghiep;
        txtVCNangKhieu.Text = customer.VC_NangKhieu;
        txtConcai.Text = customer.ConCai;
        txtVitri.Text = customer.BangCapCaoNhat;
        txtNote.Text = customer.Note;
        cbLoaiKhachHang.SelectedValue = customer.LoaiKhachHang.ToString();
    }
    private void BuildListDiaryEachMeeting(int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("ID");
        dtList.Columns.Add("CustomerID");
        dtList.Columns.Add("MeetingPlace");
        dtList.Columns.Add("Description");
        dtList.Columns.Add("LastUpdate");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;
        string strCondition = " AND 1=0";
        if (Request.QueryString["PicID"] != null && Request.QueryString["PicID"].ToString() != "" && Request.QueryString["PicID"].ToString() != "0")
            strCondition = " And CustomerID=" + Request.QueryString["PicID"].ToString();//+ " AND UserID=" + Session["logined_id"].ToString();
        DiaryEachMeeting.GetList(strCondition, "lastupdate desc", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);
        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            string[] strValues = new string[] { "", "", "", "", "" };
            dtList.Rows.Add(strValues);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                count++;
                string strID = dr["Id"].ToString();
                string CustomerID = dr["CustomerID"].ToString();
                string MeetingPlace = dr["MeetingPlace"].ToString();
                string Description = dr["Description"].ToString();
                string LastUpdate = "";
                if (dr["LastUpdate"].ToString() != "")
                    LastUpdate = "<font color=\"#0000ff\">" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("ddMMyy") + "</font>";
                string strAction = "";
                if (nPermissions >= 9)
                {
                    if (strAction.Length > 0) strAction += " - ";
                    strAction += "<a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "')\">Delete</a>";
                }

                strValues = new string[] { strID, CustomerID, MeetingPlace, Description, LastUpdate, strAction };
                dtList.Rows.Add(strValues);

            }
        }
    }
    private void LoadMeetingReadOnly()
    {
        //Repeate
        foreach (RepeaterItem item in rpDiaryEachMeeting.Items)
        {
            TextBox Description = (TextBox)item.FindControl("Description");
            TextBox MeetingPlace = (TextBox)item.FindControl("MeetingPlace");
            Description.ReadOnly = true;
            MeetingPlace.ReadOnly = true;
        }
    }
}